import { defineEventHandler, getQuery, createError } from 'h3';
import { getDbConnection } from '../../utils/db.js';
import { requireUser } from '../../utils/auth.js';

export default defineEventHandler(async (event) => {
  try {
    const { userId } = requireUser(event);

    const { noteId, versionId } = getQuery(event);
    if (!noteId || !versionId) {
      throw createError({ statusCode: 400, statusMessage: 'Note ID and Version ID are required' });
    }

    const db = await getDbConnection();
    
    // 验证笔记是否属于当前用户
    const note = await db.get(
      'SELECT id FROM notes WHERE id = ? AND user_id = ?',
      [noteId, userId]
    );
    
    if (!note) {
      throw createError({ statusCode: 404, statusMessage: 'Note not found' });
    }
    
    // 获取特定版本的内容
    const version = await db.get(
      `SELECT id, version_number, name, content, change_summary, created_at
       FROM note_versions 
       WHERE note_id = ? AND id = ?`,
      [noteId, versionId]
    );

    if (!version) {
      throw createError({ statusCode: 404, statusMessage: 'Version not found' });
    }

    return { success: true, version };
  } catch (error) {
    console.error('Error fetching note version content:', error);
    throw createError({ statusCode: 500, statusMessage: 'Failed to fetch note version content' });
  }
});
